package xin.xinny.module.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.xinny.common.datasource.DataSourceContextHolder;
import xin.xinny.common.datasource.DataSourceType;
import xin.xinny.module.entity.User;
import xin.xinny.module.service.IUserService;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lemon
 * @since 2017-09-05
 */
@Controller
@RequestMapping("")
public class UserController {

    @Autowired
    IUserService userService;

    @ResponseBody
    @RequestMapping("/list")
    public List<User> list(){
//        if(true)throw new RuntimeException("....");
        return userService.selectList(new EntityWrapper<User>());
    }

    @ResponseBody
    @RequestMapping("/insert")
    public List<User> insert(){
        userService.insert(new User(DataSourceContextHolder.getDbType()));
        return list();
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    /**
     * 需要配置produces 或者 在message-converters中将ByteArrayHttpMessageConverter位置提前
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/download",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> download() throws IOException {
        File file = new File("C:\\Users\\Administrator\\Desktop\\0816.xls");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String attachname = new String("中文文件名.xls".getBytes("UTF-8"),"iso8859-1");
        headers.setContentDispositionFormData("attachment", attachname);  //解决文件名中文乱码问题
//        headers.add("Content-Disposition","attachment;filename="+attachname);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
	
}
